/*
 * Copyright (c) 2013 Mohammad Mehdi Saboorian
 *
 * This is part of moor, a wrapper for libarchive
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */

#ifndef Archive_Reader_H
#define Archive_Reader_H

#include <string>
#include <vector>
#include <utility>

#include "CommonDef.h"

struct archive;
struct archive_entry;

class ArchiveReader
{
public:
    ArchiveReader(const std::string& archiveFileName);
	ArchiveReader(unsigned char*inBuffer, const size_t size);
    ArchiveReader(std::vector<unsigned char>&& inBuffer);
	~ArchiveReader();

	//returns false at EOF
	// destination - The destination folder path
    bool extractNext(const std::string& destination);

	//retuns empty filename at EOF
	// the first(key) is fileName, the second(value) is the data of the file
    std::pair<std::string, std::vector<unsigned char>> extractNext();

	// extract all files to destination folder 
	// destination - The destination folder path
	bool extractTo(const std::string& destination);

	// extract special files to destination folder 
	// destination - The destination folder path
	bool extractTo(const std::string& fileName, const std::string& destination);


	// this api only works if return false or exception happened,
	// return latest error code 
	int32_t getLastErrorCode() const;

	// this api only works if return false or exception happened,
	// return latest error message 
	std::string getLastError() const;

private:

	bool writeFileDataTo(const std::string& destination);
	void init();
    void checkError(const int32_t errCode, const bool closeBeforThrow = false);
	void close();

	struct archive_entry* m_entry;

	archive* m_archive;
	bool m_open;
	bool m_isFile;

    const std::string m_archiveFileName;
    std::vector<unsigned char> m_inBuffer;

	std::string m_err;
	int32_t m_code;
};

#endif

